package com.wrb.base.redis;

import com.alibaba.fastjson.JSON;
import com.wrb.base.redis.keymodel.KeyPrefix;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author wrb
 * @date 2019/11/28 10:14
 */
@Service
public class RedisService {

	@Resource(name = "jedisClientSigle")
	private JedisClient jedisClient;

	public <T> boolean set(KeyPrefix prefix, String key, T value) {
		String str = beanToString(value);
		if (str == null || str.length() <= 0) {
			return false;
		}
		//生成真正的key
		String realKey = prefix.getPrefix() + key;
		int seconds = prefix.expireSeconds();
		if (seconds <= 0) {
			jedisClient.set(realKey, str);
		} else {
			jedisClient.setex(realKey, seconds, str);
		}
		return true;
	}


	public <T> T get(KeyPrefix prefix, String key, Class<T> clazz) {
		String realKey = prefix.getPrefix() + key;
		String str = jedisClient.get(realKey);
		return stringToBean(str, clazz);
	}


	public Long hset(String key, String item, String value) {
		return jedisClient.hset(key, item, value);
	}


	public String hget(String key, String item) {
		return jedisClient.hget(key, item);
	}


	public Long incr(KeyPrefix prefix, String key) {
		String realKey = prefix.getPrefix() + key;
		return jedisClient.incr(realKey);
	}


	public Long decr(KeyPrefix prefix, String key) {
		String realKey = prefix.getPrefix() + key;
		return jedisClient.decr(realKey);
	}


	public Long expire(KeyPrefix prefix, String key, int second) {
		String realKey = prefix.getPrefix() + key;
		return jedisClient.expire(realKey, second);
	}


	public Long ttl(KeyPrefix prefix, String key) {
		String realKey = prefix.getPrefix() + key;
		return jedisClient.ttl(realKey);
	}


	public Long hdel(String key, String item) {
		return jedisClient.hdel(key, item);
	}


	public <T> boolean exists(KeyPrefix prefix, String key) {
		String realKey = prefix.getPrefix() + key;
		return jedisClient.exists(realKey);
	}


	public Long del(KeyPrefix prefix, String key) {
		String realKey = prefix.getPrefix() + key;
		return jedisClient.del(realKey);
	}

	private <T> String beanToString(T value) {
		if (value == null) {
			return null;
		}
		Class<?> clazz = value.getClass();
		if (clazz == int.class || clazz == Integer.class) {
			return "" + value;
		} else if (clazz == String.class) {
			return (String) value;
		} else if (clazz == long.class || clazz == Long.class) {
			return "" + value;
		} else {
			return JSON.toJSONString(value);
		}
	}

	@SuppressWarnings("unchecked")
	private <T> T stringToBean(String str, Class<T> clazz) {
		if (str == null || str.length() <= 0 || clazz == null) {
			return null;
		}
		if (clazz == int.class || clazz == Integer.class) {
			return (T) Integer.valueOf(str);
		} else if (clazz == String.class) {
			return (T) str;
		} else if (clazz == long.class || clazz == Long.class) {
			return (T) Long.valueOf(str);
		} else {
			return JSON.toJavaObject(JSON.parseObject(str), clazz);
		}
	}
}
